package com.algo.core.filter;

import com.algo.core.RequestContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ReferenceCountUtil;
import org.apache.log4j.Logger;

import java.util.Date;

/**
 * 负责转发请求的过滤器，具体应该包含哪些功能呢？
 * 一：需要对接注册中心，获取服务实例及其对应机器的对应关系
 * 二：解析请求路径，根据请求路径中的服务名从注册中心中拿到所有的服务实例
 * 三：基于负载均衡策略选出对应的机器转发请求
 * 四：对响应的结果进行处理
 *
 */
public class ForwardFilter implements RapidFilter {

    private static final Logger logger = Logger.getLogger(ForwardFilter.class);

    @Override
    public void doFilter(RequestContext requestContext, RapidFilterChain chain) {
        logger.info("forward filter is executing");

        // 这里是模仿构建响应
        ByteBuf buffer = Unpooled.copiedBuffer(("current time is " + new Date().getTime()).getBytes());
        HttpResponse response = new DefaultFullHttpResponse(new HttpVersion("HTTP/1.1", true),
                HttpResponseStatus.OK, buffer);

        response.headers().add("Content-Type", "text/plain; charset=UTF-8");
        response.headers().add("Content-Length", buffer.array().length);

        requestContext.getHttpRequestWrapper().getCtx().channel().writeAndFlush(response);
        requestContext.getHttpRequestWrapper().getCtx().channel().close();
        ReferenceCountUtil.release(requestContext.getHttpRequestWrapper().getRequest());

    }

    @Override
    public int getOrder() {
        return FilterOrder.FORWARD_FILTER.order;
    }

}
